import { login, logout, getInfo } from '@/api/login'
//import { getToken, setToken, removeToken } from '@/utils/auth'
import constant  from '@/utils/constant'

const user = {
  state: {
   // token: getToken(),
    token:sessionStorage.getItem(constant.sessionstorage.key.token),
    //token:sessionStorage.getItem("token"),
    name:   sessionStorage.getItem(constant.sessionstorage.key.name),
    avatar: ''    //头像
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      //state.token = token
      sessionStorage.setItem(constant.sessionstorage.key.token,token)
    },
    SET_NAME: (state, name) => {
      //state.name = name
      sessionStorage.setItem(constant.sessionstorage.key.name,name)
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    } 
  },

  actions: {
    SET_TOKEN: ({commit}, token) => {
      commit('SET_TOKEN', token)
    },

    SET_NAME: ({commit}, name) => {
      commit('SET_NAME', name)
    },
    SET_AVATAR: ({commit}, avatar) => {
      commit('SET_AVATAR', avatar)
    } ,

    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      return new Promise((resolve, reject) => {
      // console.log(" login(username, userInfo.password)")
        login(username, userInfo.password).then(response => {
           console.log(response)
          const token = response.token
          //console.log("token = "+token)
          //头像   --效果
          //commit('SET_AVATAR', 'http://oa.ossjk.cn/stuImgs/stuImgs/tst/firstCategoryPicture/20180408/20180408112010_4489.png') 
          //setToken( token)
          commit('SET_TOKEN', token)

          commit('SET_NAME', username)
          //硬编码
          commit('SET_AVATAR', "http://oa.ossjk.cn/stuImgs/stuImgs/tst/firstCategoryPicture/20180408/20180408112010_4489.png")
         
          resolve()
        }).catch(error => {
         // console.log(error)
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          console.log(response)
          const data = response.data
           
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', "http://oa.ossjk.cn/stuImgs/stuImgs/tst/firstCategoryPicture/20180408/20180408112010_4489.png")
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      console.log("登出");
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          resolve()
        }).catch(error => {
          console.log(error);
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        resolve()
      })
    },
  
  }
}

export default user
